package com.atguigu;

public class Test2 {

	public static void main(String[] args) {
		final Num2 num = new Num2();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						
						num.addNum();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "AA").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						num.deNum();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "BB").start();
		
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						num.addNum();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "CC").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					try {
						num.deNum();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "DD").start();


	}

}

class Num2 {

	private int n = 0;

	public synchronized void addNum() throws InterruptedException {
		while (n != 0) {
			wait();
		}
		System.out.println(Thread.currentThread().getName() + "n的值为" + ++n);
		notify();
	}

	public synchronized void deNum() throws InterruptedException {
		while (n != 1) {
			wait();
		}
		System.out.println(Thread.currentThread().getName() + "n的值为" + --n);
		notify();
	}

}